import MyModal from "@/components/MyModal";
import { RoomTypeEnum } from "@/constants/enum";
import { IDCardReg, PhoneReg } from "@/constants/reg";
import { addAccommodation } from "@/services/Accommodation/accommodation";
import { getOptionalTime } from "@/services/customer/customer";
import { getFloorList } from "@/services/floor/floor";
import { getRoomList } from "@/services/room/room";
import { useBoolean, useRequest } from "ahooks";
import { Cascader, DatePicker, Form, Input, Select, message } from "antd";
import dayjs from "dayjs";
import { useEffect, useMemo, useRef, useState } from "react";
const { RangePicker } = DatePicker;
const  isBetween = require('dayjs/plugin/isBetween')
dayjs.extend(isBetween)
export default ({ open, close, refresh }) => {
  const [form] = Form.useForm();
  const [loading, { toggle: toggleLoading }] = useBoolean(false);
  const { data: floorList } = useRequest(getFloorList);
  const { data: roomList, run: getRoom } = useRequest(getRoomList, {
    manual: true,
  });
  const [roomType,setRoomType] =useState('')
  const today = dayjs(); //今天
  const floorId = Form.useWatch("floorId", form);
  const roomId = Form.useWatch("roomId", form);
  const time = Form.useWatch("time", form);
  const [roomPrice,setRoomPrice] = useState(void 0);//房屋单价
  const onOk = async () => {
    const values = await form.validateFields();
    values.stayStartByTime = values.time[0].valueOf();
    values.stayEndtByTime = values.time[1].valueOf();
    delete values.time;
    toggleLoading();
    try {
      await addAccommodation({ ...values });
      message.success("办理成功");
      form.resetFields()
      close();
      refresh();
    } finally {
      toggleLoading();
    }
  };
  useEffect(() => {
    let money = void 0;
    if (time) {
      const days = time?.[1].diff(time?.[0], "day");
      money = days === 0 ? roomPrice : roomPrice * days;
    }
    form.setFieldValue('houseCosts',money)
  }, [time, roomPrice]);
  const { data: optionalTime } = useRequest(
    () => {
      if (!roomId) return [];
      return getOptionalTime({ roomId });
    },
    {
      refreshDeps: [roomId],
    }
  );
  const isDisableDate = (d) =>{
    return d.isBefore(today) ||optionalTime.includes(dayjs(d).format("YYYY-MM-DD"))
  }
  return (
    <MyModal
      title={"办理入住"}
      open={open}
      close={close}
      onOk={onOk}
      confirmLoading={loading}
    >
      <Form form={form} wrapperCol={{ span: 24 }} layout="vertical">
        <Form.Item
          name="realName"
          rules={[
            {
              required: true,
            },
          ]}
          label="姓名"
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          name="tel"
          rules={[
            {
              required: true,
            },
            {
              pattern: PhoneReg,
              message: "请输入正确的手机号码",
            },
          ]}
          label="电话"
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          name="identifyNum"
          rules={[
            {
              required: true,
            },
            {
              pattern: IDCardReg,
              message: "请输入正确的身份证号码",
            },
          ]}
          label="身份证号码"
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          name="floorId"
          label="楼层"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Select
            onChange={(v) => {
              getRoom(v);
            }}
            options={floorList}
            fieldNames={{
              label: "floorName",
              value: "floorId",
            }}
            placeholder="请选择"
          />
        </Form.Item>
        {!!floorId && (
          <>
            <Form.Item
              name="roomId"
              label="房间"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Select
                options={roomList}
                fieldNames={{
                  label: "roomNum",
                  value: "roomId",
                }}
                placeholder="请选择"
                onChange={(v, r) => {
                  setRoomPrice(r.roomPrice)
                  setRoomType(r.roomTypeName)
                }}
              />
            </Form.Item>
            {
              roomId&&<Form.Item
              label="房间类型"
            >
              {roomType}
            </Form.Item>
            }
            
            <Form.Item
              name="time"
              label="入住时间-退房时间"
              rules={[
                {
                  required: true,
                  validator: (rule, value) => {
                    if (value[0] && value[1] && !value[0].isBefore(value[1])) {
                      return Promise.reject("退房时间不能等于入住时间");
                    }
                    if(optionalTime?.find(i=>dayjs(i).isBetween(value[0],value[1]))){
                      return Promise.reject("预定时间不能包含已被预定时间")
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <RangePicker
               allowClear={false}
                disabledDate={(d) =>
                  isDisableDate(d)
                }
              />
            </Form.Item>
            {!!time && (
              <Form.Item
                name="houseCosts"
                rules={[
                  {
                    required: true,
                  },
                ]}
                label="金额"
              >
                <Input
                  readOnly
                  style={{ width: "200px" }}
                  prefix="￥"
                  suffix="RMB"
                />
              </Form.Item>
            )}
          </>
        )}
      </Form>
    </MyModal>
  );
};
